package org.px.gui;

import org.px.domain.Department;
import org.px.domain.UserIdentity;
import org.px.service.DepartmentService;
import org.px.service.UserDao;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.List;

public class RegisterFrame extends JFrame {
    private JTextField userIdField;
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JComboBox<String> userTypeCombo;
    private UserDao userDao = new UserDao();
    private LoginFrame loginFrame;
    private JComboBox<Department> deptCombo;
    private JLabel deptLabel;

    public RegisterFrame(LoginFrame loginFrame) {
        this.loginFrame = loginFrame;
        initUI();
    }
    
    private void initUI() {
        setTitle("员工请假管理系统 - 注册");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(loginFrame);
        
        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        
        // 用户ID标签和输入框
        gbc.gridx = 0;
        gbc.gridy = 0;
        panel.add(new JLabel("用户ID:"), gbc);
        
        gbc.gridx = 1;
        userIdField = new JTextField(20);
        panel.add(userIdField, gbc);
        
        // 用户名标签和输入框
        gbc.gridx = 0;
        gbc.gridy = 1;
        panel.add(new JLabel("用户名:"), gbc);
        
        gbc.gridx = 1;
        usernameField = new JTextField(20);
        panel.add(usernameField, gbc);
        
        // 密码标签和输入框
        gbc.gridx = 0;
        gbc.gridy = 2;
        panel.add(new JLabel("密码:"), gbc);
        
        gbc.gridx = 1;
        passwordField = new JPasswordField(20);
        panel.add(passwordField, gbc);
        
        // 用户类型标签和下拉框
        gbc.gridx = 0;
        gbc.gridy = 3;
        panel.add(new JLabel("用户类型:"), gbc);

        gbc.gridx = 1;
        userTypeCombo = new JComboBox<>(new String[]{"管理员", "员工"});
        userTypeCombo.addActionListener(e -> toggleDepartmentField()); //切换监听
        panel.add(userTypeCombo, gbc);

        // 新增部门选择标签和下拉框
        gbc.gridx = 0;
        gbc.gridy = 4;
        deptLabel = new JLabel("所属部门:");//部门选择标签
        panel.add(deptLabel, gbc);

        gbc.gridx = 1;
        deptCombo = new JComboBox<>();
        try {
            List<Department> departments = new DepartmentService().getAllDepartments();
            if (departments.isEmpty()) {
                // 添加提示信息，告知用户没有可用的部门数据
                JOptionPane.showMessageDialog(this, "当前没有可用的部门数据，请联系管理员", "提示", JOptionPane.INFORMATION_MESSAGE);
            } else {
                deptCombo.setModel(new DefaultComboBoxModel<>(departments.toArray(new Department[0])));
            }
        } catch (SQLException ex) {
            // 异常处理和日志记录
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载部门数据失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
        panel.add(deptCombo, gbc);
        deptLabel.setVisible(false);
        deptCombo.setVisible(false);

        // 注册按钮
        gbc.gridx = 0;
        gbc.gridy = 5;
        gbc.gridwidth = 2;
        JButton registerBtn = new JButton("注册");
        registerBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                doRegister();
            }
        });
        panel.add(registerBtn, gbc);
        
        // 返回登录按钮
        gbc.gridy = 6;
        JButton backBtn = new JButton("返回登录");
        backBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        panel.add(backBtn, gbc);
        
        add(panel);
    }

    private void toggleDepartmentField() {
        boolean isEmployee = "员工".equals(userTypeCombo.getSelectedItem());
        deptLabel.setVisible(isEmployee);
        deptCombo.setVisible(isEmployee);
        revalidate(); // 新增界面刷新
        repaint();
    }

    private void doRegister() {
        String user_id = userIdField.getText().trim();
        String username = usernameField.getText().trim();
        String password = new String(passwordField.getPassword());
        String user_type = (String) userTypeCombo.getSelectedItem();
        Department department = (Department) deptCombo.getSelectedItem();

        if (user_id.isEmpty() || username.isEmpty() || password.isEmpty()) {
            JOptionPane.showMessageDialog(this, "所有字段均不能为空", "注册错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (user_type.equals("员工") && department == null) { // 新增部门校验
            JOptionPane.showMessageDialog(this, "员工必须选择所属部门", "注册错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try {
            // 检查用户ID是否已存在
            if (userDao.isUserIdExists(user_id)) {
                JOptionPane.showMessageDialog(this, "用户ID已存在，请更换", "注册错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            // 检查用户名是否已存在
            if (userDao.isUsernameExists(username)) {
                JOptionPane.showMessageDialog(this, "用户名已存在，请更换", "注册错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            // 创建用户对象
            UserIdentity user = new UserIdentity();
            user.setUser_id(user_id);
            user.setUsername(username);
            user.setPassword(password);
            user.setUser_type("员工".equals(user_type) ? "employee" : "admin");
            
            if (userDao.register(user)) {
                if ("员工".equals(user_type)) {
                    if (deptCombo.getSelectedItem() == null) { // 强化空值校验
                        JOptionPane.showMessageDialog(this, "请选择所属部门", "注册错误", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    Department selectedDept = (Department) deptCombo.getSelectedItem();
                    System.out.println("Selected Department ID: " + selectedDept.getDept_name());
                    // 添加员工部门关联信息
                    if (!userDao.addEmployee(user.getUser_id(), user.getUsername(), selectedDept.getDept_id())) {
                        userDao.deleteUser(user.getUser_id());
                        JOptionPane.showMessageDialog(this, "部门信息关联失败", "注册错误", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                }
                JOptionPane.showMessageDialog(this, "注册成功，请登录", "提示", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            } else {
                JOptionPane.showMessageDialog(this, "注册失败，请重试", "注册错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库操作异常：" + ex.getMessage(), "系统错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}